package com.hunttown.mes.dao;

import com.hunttown.common.dao.base.BaseDao;
import com.hunttown.common.domain.Query;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.stereotype.Repository;

import java.util.List;
import java.util.Map;

/**
 * created by wangjunfu on 2019-01-29 16:13:45
 */
@Repository
public class AnalysisMysqlQueryDao extends BaseDao {
    private static final Logger logger = LoggerFactory.getLogger(AnalysisMysqlQueryDao.class);

    // 直接通过SQL去获取数据，然后以 Map 的形式返回结果
    public List<Map<String, String>> execQuery(final String execSql) {
        Query query = Query.noPage();
        query.put("execSql", execSql);

        System.out.println("------ print query ------");
        System.out.println(execSql);

        List<Map<String, String>> map = queryForList("AnalysisMysqlQuery.selectBySql", query);
        return map;
    }

    public List<Map<String, String>> execQuery(final Query query) {
        List<Map<String, String>> map = queryForList("AnalysisMysqlQuery.selectByQuery", query);
        return map;
    }

    // 查询总记录数
    public Long countQuery(final String execSql) {
        Query query = Query.noPage();
        query.put("execSql", execSql);

        return queryForObject("AnalysisMysqlQuery.countBySql", query);
    }

    //按日期创建一张表，并且将符合条件的(create_time)数据插入到该表中（不区分哪个企业的）
    public void backupTableByDate(final Query query) {
        String execSql = String.format("CREATE TABLE `%s`.`%s` SELECT * FROM `%s`.`%s` WHERE date(create_time) <= '%s';", query.get("dbName"), query.get("toTable"), query.get("dbName"), query.get("fromTable"), query.get("createTime"));
        Query execQuery = Query.noPage();
        execQuery.put("execSql", execSql);

        System.out.println("------ print create sql ------");
        System.out.println(execSql);

        insert("AnalysisMysqlQuery.deleteInformationByDate", execQuery);
    }

    //删除符合条件的(create_time)数据（不区分哪个企业的）
    public void deleteInformationByDate(final Query query) {
        String execSql = String.format("DELETE FROM `%s`.`%s` WHERE date(create_time) <= '%s';", query.get("dbName"), query.get("fromTable"), query.get("createTime"));
        Query execQuery = Query.noPage();
        execQuery.put("execSql", execSql);

        System.out.println("------ print delete sql ------");
        System.out.println(execSql);

        delete("AnalysisMysqlQuery.deleteInformationByDate", execQuery);
    }
}